<template>
  <div class="login-page">
    <van-nav-bar class="top"
    title="账号登录"
  left-arrow
  @click-left="onClickLeft"
/>
    <van-form @submit="onSubmit">
  <van-field
    v-model="username"
    name="username"
    placeholder="用户名"
    :rules="[
      { required: true, message: '请填写用户名' },
      { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符'}
      ]"
  />
  <!-- 1.用正则校验 -->
  <!-- { pattern: /^\d{11}$/, message: '手机号格式错误'} -->
   <!-- 2.用自定义函数校验
      { validator: valiFn, message: '手机号格式错误'} -->
  <van-field
    v-model="password"
    type="password"
    name="password"
    placeholder="密码"
    :rules="[
      { required: true, message: '请填写密码' },
      { pattern: /^\w{6,}$/, message: '密码至少包含6个字符'}
  ]"
  />
  <div style="margin: 16px;">
    <van-button class="sub"   block type="info" native-type="submit">提交</van-button>
  </div>
</van-form>
<router-link class="link" to="/register">还没有账号,去注册~</router-link>
  </div>
</template>

<script>
import  {loginApi} from '@/api/user'
import {setItem, key} from '@/utils/storage.js'
export default {
  name: 'login-page',
  data () {
    return {
      username:'',
      password:'',
    }
  },
  methods: {
   async onSubmit(values) {
      console.log('values', values)
      try {
        const res = await loginApi(values)
        console.log(res);
        // console.log(token);
        setItem(key,res.body.token) //将token存储本地
        this.$router.push('/home/my')
        this.$toast('登录成功')
      }catch(e) {
       console.log(e);
      }
    },
    // valiFn(val) {
    //  return /^\d{11}$/.test(val)
    // },
    onClickLeft() {
      this.$router.push({
        path:'/home/my'
      })
    },
  }
}
</script>

<style lang="less" scoped>
.top {
 background-color:#21b97a;
}
.link {
  color: #666;
  font-size: 14px;
  margin-left: 30%;
 
}
.sub{
  background-color: #21b97a;
}
</style>
